<template>
  <div class="app-container" :loading="pageLoading">
    <el-form
      ref="formRef"
      :model="data.formModel"
      label-position="top"
      :inline="true"
      :rules="rules"
      :scroll-to-error="true"
    >
      <div class="divide-title">公司信息</div>

      <el-form-item label="父公司名称:" prop="parentId">
        <ApiSelect
          v-model="data.formModel.parentId"
          :options="companyOptions"
          valueField="companyId"
          labelField="name"
          :disabled="route.query.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="公司名称:" prop="name">
        <el-input v-model="data.formModel.name" placeholder="公司名称" />
      </el-form-item>
      <el-form-item label="公司账号:" prop="companyAccount">
        <el-input
          maxlength="11"
          v-model="data.formModel.companyAccount"
          placeholder="公司账号"
          :disabled="route.query.id ? true : false"
        />
      </el-form-item>
      <el-form-item label="合作模式:" prop="cooperationMode">
        <el-select v-model="data.formModel.cooperationMode" placeholder="请选择">
          <el-option
            v-for="dict in sys_cooperation"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-tree-select
          v-model="data.formModel.deptId"
          :data="departmentsOptions"
          check-strictly
          :props="CascaderProps"
          :render-after-expand="false"
          clearable
          @change="changeCity"
        />
      </el-form-item>
      <el-form-item label="公司地址:" prop="address">
        <MapInput
          v-model:value="data.formModel.address"
          v-model:lng="data.formModel.longitude"
          v-model:lat="data.formModel.latitude"
        />
      </el-form-item>
      <el-form-item label="状态:" prop="enabled">
        <el-select v-model="data.formModel.enabled" placeholder="请选择">
          <el-option
            v-for="dict in sys_common_staus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公司法人:" prop="legalPerson">
        <el-input v-model="data.formModel.legalPerson" placeholder="公司法人" />
      </el-form-item>
      <el-form-item label="法人联系方式:" prop="lglPsnMobile">
        <el-input maxLength="11" v-model="data.formModel.lglPsnMobile" placeholder="联系方式" />
      </el-form-item>
      <el-form-item label="公司负责人:" prop="contacts">
        <el-input v-model="data.formModel.contacts" placeholder="公司负责人" />
      </el-form-item>
      <el-form-item label="负责人联系方式:" prop="mobile">
        <el-input maxLength="11" v-model="data.formModel.mobile" placeholder="联系方式" />
      </el-form-item>
      <el-form-item label="合同开始时间:" prop="contractBeginDate">
        <el-date-picker
          v-model="data.formModel.contractBeginDate"
          type="date"
          placeholder="合同开始时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="合同到期时间:" prop="contractEndDate">
        <el-date-picker
          v-model="data.formModel.contractEndDate"
          type="date"
          placeholder="合同到期时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item class="licence" label="营业执照有效期:" required>
        <el-form-item prop="bizLicenceBeginTime" style="margin-right: 5px">
          <el-date-picker
            v-model="data.formModel.bizLicenceBeginTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="开始时间"
          />
        </el-form-item>
        ~ &nbsp;
        <el-form-item prop="bizLicenceEndTime" style="margin-right: 5px">
          <el-date-picker
            v-model="data.formModel.bizLicenceEndTime"
            placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="longTerm">
          <el-checkbox v-model="data.formModel.longTerm" label="长期" />
        </el-form-item>
      </el-form-item>
      <el-form-item label="经营许可证:" prop="manageLicence">
        <ImageUpload v-model="data.formModel.manageLicence" :limit="1" :fileSize="30" />
      </el-form-item>
      <el-form-item label="公司营业执照:" prop="bizLicence">
        <ImageUpload v-model="data.formModel.bizLicence" :limit="1" :fileSize="30" />
      </el-form-item>

      <div class="divide-title">支付信息</div>
      <el-form-item label="支付方式:" prop="paymentCode">
        <el-select v-model="data.formModel.paymentCode" placeholder="请选择">
          <el-option
            v-for="dict in sys_payment"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <div class="pay-block justify-space-around">
        <div class="part">
          <h5>微信账号配置</h5>
          <el-form-item maxlength="50" label="微信支付商号:" prop="wxMchId">
            <el-input v-model="data.formModel.wxMchId" placeholder="微信支付商号" />
          </el-form-item>
          <el-form-item maxlength="50" label="API密钥:" prop="apiSecret">
            <el-input v-model="data.formModel.apiSecret" placeholder="API密钥" />
          </el-form-item>
          <el-form-item label="证书路径:" prop="certPath">
            <FileUpload v-model="data.formModel.certPath" :limit="1" :fileSize="30" />
          </el-form-item>
        </div>
        <div class="part">
          <h5>支付宝账号配置</h5>
          <el-form-item label="支付宝应用ID:" prop="appId">
            <el-input maxlength="50" v-model="data.formModel.appId" placeholder="支付宝应用ID" />
          </el-form-item>
          <el-form-item label="应用公钥证书:" prop="appPrivateKeyFile">
            <FileUpload v-model="data.formModel.appPrivateKeyFile" :limit="1" :fileSize="30" />
          </el-form-item>
          <el-form-item label="支付宝公钥证书:" prop="aliPublicKey">
            <FileUpload v-model="data.formModel.aliPublicKey" :limit="1" :fileSize="30" />
          </el-form-item>
          <el-form-item label="应用私钥:" prop="appPrivateKey">
            <el-input
              maxlength="50"
              v-model="data.formModel.appPrivateKey"
              placeholder="应用私钥"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="btn-group justify-center">
      <el-button @click="formAction(false)">取消</el-button>
      <el-button :loading="loading" type="primary" @click="formAction(true)">确定</el-button>
    </div>
  </div>
</template>

<script setup name="AddCompany">
import { formRule } from './index'
import { addCompany, getCompanyInfo, updateCompany } from '@/api/organization/company'
import useUserStore from '@/store/modules/user'
import { formRules } from '@/utils/valid/formRules'
import { handleUpdConfirm } from '@/utils/tools'

const route = useRoute()
const useStore = useUserStore()
const departmentsOptions = ref([])
const id = route.query.id //编辑公司id
const { proxy } = getCurrentInstance()
const { sys_payment, sys_cooperation, sys_common_staus } = proxy.useDict(
  'sys_payment',
  'sys_cooperation',
  'sys_common_staus'
)
const CascaderProps = {
  value: 'deptId',
  label: 'deptName',
  children: 'children'
}
const companyOptions = computed(() => {
  let options = [{ companyId: '0', name: '无' }]
  if (useStore.companys.length) options = options.concat(useStore.companys)
  return options
})
const formRef = ref(null)
const loading = ref(false)
const pageLoading = ref(false)
const rules = ref({
  ...formRule,
  bizLicenceEndTime: { validator: validateRangeTime, trigger: 'blur' },
  contractEndDate: [
    formRules.set('请选择合同到期时间', 'change'),
    { validator: validateRangeTime1, trigger: 'blur' }
  ]
})
const data = reactive({
  formModel: {
    parentId: '',
    longitude: '',
    latitude: ''
  }
})
import { listDept } from '@/api/system/dept'
/** 获取部门数据 */
function getDepartments() {
  console.log(11111111)
  listDept().then((response) => {
    console.log({ response })
    departmentsOptions.value = proxy.handleTree(response.data, 'deptId')
  })
}
// function changeCity() {
//   console.log(data.formModel.deptId)
// }

// 获取公司详情
watch(
  () => route.query.id,
  async (id) => {
    if (id) {
      pageLoading.value = true
      try {
        const r = await getCompanyInfo(id)
        if (r?.data) {
          const { companys, alipayInfo = {}, wxpayInfo = {} } = r?.data ?? {}
          data.formModel = {
            ...companys,
            ...alipayInfo,
            ...wxpayInfo,
            longTerm: companys?.longTerm == 1
          }
        }
      } catch (error) {
        console.log(error)
      } finally {
        pageLoading.value = false
      }
    }
  },
  {
    immediate: true
  }
)

watchEffect(() => {
  if (data.formModel.longTerm) data.formModel.bizLicenceEndTime = ''
})

watchEffect(() => {
  if (data.formModel.bizLicenceEndTime) data.formModel.longTerm = false
})

// 时间验证
function validateRangeTime(rule, value, cb) {
  const { bizLicenceEndTime, longTerm, bizLicenceBeginTime } = data.formModel
  if (!bizLicenceEndTime && !longTerm) {
    return cb(new Error('请选择营业执照结束时间或勾选长期'))
  }
  if (bizLicenceEndTime && bizLicenceBeginTime && bizLicenceBeginTime >= bizLicenceEndTime) {
    return cb(new Error('营业执照开始结束时间冲突'))
  }
  cb()
}
function validateRangeTime1(rule, value, cb) {
  const { contractBeginDate, contractEndDate } = data.formModel
  if (contractBeginDate && contractEndDate && contractBeginDate >= contractEndDate) {
    return cb(new Error('合同开始结束时间冲突'))
  }
  cb()
}

function formAction(confirm) {
  if (confirm) {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        if (!data.formModel.longitude) {
          proxy.$modal.msgError('请使用地图选址获取公司地址定位信息')
          return
        }

        handleUpdConfirm(!id, '确认要修改当前公司？').then(async () => {
          loading.value = true
          const fetchMethod = id ? updateCompany : addCompany
          const { createTime, ..._data } = data.formModel
          try {
            const r = await fetchMethod({
              ..._data,
              longTerm: data.formModel.longTerm ? 1 : 0
            })
            if (r) {
              proxy.$modal.msgSuccess(id ? '更新成功' : '新增成功')

              setTimeout(() => proxy.$tab.closeOpenPage({ path: '/organization/company' }), 1000)
              // 更新useStore公司列表数据
              useStore.getAllCompany()
            }
          } finally {
            loading.value = false
          }
        })
      }
    })
  } else {
    proxy.$tab.closeOpenPage({ path: '/organization/company' })
  }
}
getDepartments()
</script>

<style lang="scss" scoped>
.pay-block {
  width: 100%;
  display: flex;
}
.btn-group {
  width: 100%;
  margin: 30px 0;
  .el-button {
    margin: 0 30px;
    padding: 0 2em;
  }
}
:deep(.el-input-group__append) {
  background-color: #fff;
  color: var(--el-color-primary);
}
.licence :deep(.el-form-item__content .el-form--inline .el-form-item) {
  margin-right: 5px;
}
</style>
